# -*- coding:utf-8 -*-
from twisted.internet import defer, task
from twisted.internet.protocol import Protocol, ClientFactory
import random, sys, math, hmac, time
from twisted.internet import reactor


def idBuild(head, num, now):
    zero = ''
    for z in range(num - len(str(now))):
        zero = zero + '0'
    finalId = head + zero + str(now)
    return finalId

baId = [idBuild("BS", 6, x) for x in range(1024)]
command = ['besd']


def reHandler(command, lcId):
    if command == "lnon":
        return "lron,%s" % lcId
    elif command == "lnof":
        return "lrof,%s" % lcId
    else:
        return None


# 请求协议
class PoetryProtocol(Protocol):
    num = 0

    def __init__(self):
        pass

    def dataSend(self, data=''):
        print "send data base:", self.id
        string = ''

        if data == '':
            # string = "BS000001,lckw,12345678,12,17"
            # string = "BS000001,lrof,123456789"
            string = "%s,%s,%s,%s,%s" % (self.id, random.sample(command, 1)[0], random.randint(0, 99), random.randint(0, 99), random.randint(0, 99))
        else:
            string = data
        # string = "BS000002,breg"
        key = hmac.new("2e0160e078aa4b925e62b20610378253")
        key.update(string)
        newstr = string + "," + key.hexdigest()

        length = len(newstr)

        newstr = str(length) + newstr
        print newstr
        self.transport.write(newstr)

    def connectionMade(self):
        se = random.randint(1, 100)
        self.id = baId[self.factory.kk]
        self.factory.kk += 1

        cb = self.dataSend
        reactor.callLater(1, cb)
        # reactor.callInThread(self.dataSend)
        # self.dataSend('%s,besd,12345678' % self.id)
        # se = random.randint(0, 30)
        # l = task.LoopingCall(self.dataSend)
        # print "start se: %s  baId: %s" % (se, self.id)
        # l.start(se)

    def connectionLost(self, reason):
        self.factory.data_finished(self.id)

    def dataReceived(self, data):
        print data
        print self.num
        self.num += 1
        if self.num < 10:
            self.dataSend()
        # data = data.split(",")
        # command = data[1]
        # if command == "bell":
        #     self.dataSend(self.id + "," + "extr")
        #     # self.dataSend()
        # elif command == "over":
        #     # self.connectionLost("")
        #     self.dataSend()
        # elif command == "ok":
        #     self.dataSend()
        #     # self.dataSend(self.id + "," + "extr")
        # elif command != "over":
        #     reCommand = reHandler(command, data[2])
        #     if reCommand is not None:
        #         self.dataSend(self.id + "," + reCommand)
        #     self.dataSend(self.id + "," + "extr")



# 请求协议工厂类
class FanClientFactory(ClientFactory):
    protocol = PoetryProtocol

    def __init__(self):
        self.kk = 0

    def data_finished(self, data):
        print 'lost service....', data


def get_data(host, port, factory):
    reactor.connectTCP(host, port, factory)


if __name__ == '__main__':
    server = '127.0.0.1'
    # server = '192.168.1.5'
    # server = '115.47.123.228'
    addresses = []
    for i in range(100):
        addresses.append((server, 8080))

    factory = FanClientFactory()
    for address in addresses:
        host, port = address
        get_data(host, port, factory)

    reactor.run()
